package com.rzt.service;

import com.rzt.db.DBContextHolder;
import com.rzt.db.DynamicDataSource;
import com.rzt.entity.DataSource;
import com.rzt.moredb.entity.DbMsg;
import com.rzt.repository.DataSourceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * @author Zhao Yi
 * @version 1.0
 * @date 2020/12/20 21:31
 **/
@Service
@Slf4j
public class DataSourceService {
    @Autowired
    private DataSourceRepository dataSourceRepository;

    @Autowired
    @Qualifier("dynamicDataSource")
    private DynamicDataSource dynamicDataSource;

    @Autowired
    private DbMsgService dbMsgService;

    /**
     * 获取所有数据源
     *
     * @return
     */
    public List<DataSource> listDataSource() {
        return dataSourceRepository.findAll();
    }

    /**
     * 获取所有数据源
     *
     * @return
     */
    @Transactional
    public void addDataBase() {
        DataSource db = new DataSource(null,"MOREDB1",
                "123456","jdbc:oracle:thin:@127.0.0.1:1521:orcl",
                "oracle.jdbc.driver.OracleDriver","oracle");
        dataSourceRepository.save(db);
    }

    /**
     * 使用数据源1
     */
    public void useMoredb(String id) throws Exception {
        DataSource db = dataSourceRepository.findById(id).get();
        dynamicDataSource.createDataSourceWithCheck(db);
        DBContextHolder.setDataSource(db.getId());

        //save
        DbMsg msg = new DbMsg();
        msg.setMsg("使用数据源1成功添加！");
        msg.setCreateTime(new Date());
        dbMsgService.save(msg);

        //search
        DbMsg msg1 = dbMsgService.findById(msg.getId());
        log.info("已经插入数据："+msg1);

    }
}
